<?php

/**
 * 推荐位文章管理model操作
 * @author  xiaobai
 * @date    2018-01-28
 */

namespace app\common\model;

use app\common\model\Common;

class PositionData extends Common
{
    const THUMB_YES    = 1;     // 存在缩略图
    const THUMB_NO     = 0;     // 不存在缩略图

    const TYPE_NEWS    = 1;     // 文章
    const TYPE_PRODUCT = 2;     // 产品

    const STATUS_ISSUE = 1;     // 发布状态
    const STATUS_DRAFT = 0;     // 草稿状态

    protected $pk     = 'id';
    protected $insert = ['create_time'];

    //返回原有数据  不自动进行时间转换
    public function getCreateTimeAttr($time)
    {
        return $time;
    }

    /**
     * 获取页面静态数据
     * @return array
     */
    public function getStaticData()
    {
        $types = array(
            self::TYPE_NEWS    => '文章',
            self::TYPE_PRODUCT => '产品',
        );

        return array('types'=>$types);
    }

    /**
     * 写入推荐位对应的文章管理内容
     * @author xiaobai
     * @date   18-01-28
     * @param  array $news_data     文章信息
     * @return array
     */
    public function setPositionData($news_data = array(), $position_ids = '')
    {
        $new_data = array(
            'title'    => $news_data['title'],
            'subtitle' => $news_data['subtitle'],
            'thumb'    => !empty($news_data['thumb']) ? $news_data['thumb'] : '',
        );
        $data = array();
        // 存在推荐位处理要添加的内容
        $pos_data = $position_ids;
        if (!empty($pos_data)) {
            $pos_data = explode(',', $pos_data);
            foreach ($pos_data as $k=>$v) {
                $data[$k]['position_id'] = $v;
                $data[$k]['column_id']   = $news_data['column_id'];
                $data[$k]['news_id']     = $news_data['id'];
                $data[$k]['thumb']       = !empty($news_data['thumb']) ? self::THUMB_YES : self::THUMB_NO;
                $data[$k]['data']        = json_encode($new_data, JSON_UNESCAPED_UNICODE);
                $data[$k]['status']      = $news_data['status'];
                $data[$k]['admin_id']    = get_admin_id();
                $data[$k]['create_time'] = date('Y-m-d H:i:s');
            }
        }

        $is_del = $this->where(array('news_id'=>$news_data['id']))->delete();
        if ($is_del === false) {
            return array('code'=>0, 'msg'=>'清除当前文章之前推荐信息错误');
        }

        // 如果没有推荐位信息删除成功后直接返回
        if (count($data) <= 0) {
            return array('code'=>1);
        }

        // 执行保存
        if ($this->saveAll($data)) {
            return array('code'=>1);
        }
        return array('code'=>0, 'msg'=>'添加文章推荐位信息超时，请重新操作');
    }

    /**
     * 保存推荐位数据
     * @param array $sub_data   待保存数据
     * @param int $type         类型，默认文章
     * @return array
     */
    public function savePositionData($sub_data = array(), $type = self::TYPE_NEWS)
    {
        $new_data = $this->_handleConData($sub_data, $type);
        if (empty($new_data) || count($new_data) <= 0) {
            return array('code'=>1);
        }
        $data = array();
        // 存在推荐位处理要添加的内容
        $pos_data = !empty($sub_data['position_ids']) ? $sub_data['position_ids'] : '';
        if (!empty($pos_data)) {
            $pos_data = explode(',', $pos_data);
            foreach ($pos_data as $k=>$v) {
                $data[$k] = $this->_handlePosData($v, $sub_data, $new_data, $type);
            }
        }

        $is_del = $this->where(array('news_id'=>$sub_data['id']))->delete();
        if ($is_del === false) {
            return array('code'=>0, 'msg'=>'清除当前内容之前推荐信息错误');
        }

        // 如果没有推荐位信息删除成功后直接返回
        if (count($data) <= 0) {
            return array('code'=>1);
        }

        // 执行保存
        if ($this->saveAll($data)) {
            return array('code'=>1);
        }
        return array('code'=>0, 'msg'=>'添加内容推荐位信息超时，请重新操作');
    }

    /**
     * 处理内容数据
     * @param array $data   待处理数据
     * @param int $type     类型，默认文章类型
     * @return array
     */
    public function _handleConData($data = array(), $type = self::TYPE_NEWS)
    {
        $result = array();
        if ($type == self::TYPE_NEWS) {
            $result = array(
                'title'    => $data['title'],
                'subtitle' => isset($data['subtitle']) ? $data['subtitle'] : '',
                'thumb'    => !empty($data['thumb']) ? $data['thumb'] : '',
            );
        }

        if ($type == self::TYPE_PRODUCT) {
            $result = array(
                'title'             => $data['title'],
                'earnings'          => $data['earnings'],
                'cooperation_money' => $data['cooperation_money'],
                'period'            => $data['period'],
                'thumb'             => !empty($data['thumb']) ? $data['thumb'] : '',
                'is_hot'            => $data['is_hot']
            );
        }

        return $result;
    }

    /**
     * 处理保存内容数据
     * @param int $position_id  推荐位id
     * @param array $data       待处理数据
     * @param array $new_data   存储内容数据
     * @param int $type         类型，默认文章类型
     * @return array
     */
    public function _handlePosData($position_id = 0, $data = array(), $new_data = array(), $type = self::TYPE_NEWS)
    {
        $result = array();
        $result['position_id'] = $position_id;
        $result['news_id']     = $data['id'];
        $result['data']        = json_encode($new_data, JSON_UNESCAPED_UNICODE);
        $result['admin_id']    = get_admin_id();
        $result['type']        = $type;
        $result['create_time'] = date('Y-m-d H:i:s');

        if ($type == self::TYPE_NEWS) {
            $result['column_id'] = $data['column_id'];
            $result['thumb']     = !empty($data['thumb']) ? self::THUMB_YES : self::THUMB_NO;
            $result['status']    = $data['status'];
        }

        if ($type == self::TYPE_PRODUCT) {
            $result['column_id'] = 0;
            $result['thumb']     = !empty($data['thumb']) ? self::THUMB_YES : self::THUMB_NO;
            $result['status']    = $data['status'];
        }

        return $result;
    }

    /**
     * 获取推荐位数据信息
     * @param int $position_id  推荐位id
     * @param int $limit        获取数量
     * @param string $is_thumb  缩略图要求，all全部
     * @param int $type         类型，默认文章
     * @param int $cache_time   缓存时间
     * @return array|false|mixed|\PDOStatement|string|\think\Collection
     */
    public function getPositionData($position_id = 0, $limit = 4, $is_thumb = 'all', $type = self::TYPE_NEWS, $cache_time = 3600*24*7)
    {
        $key  = 'getPositionData_'.$position_id.'_'.$limit.'_'.$is_thumb.'_'.$type.'_'.$cache_time;
        $list = cache($key);
        if (empty($list)) {
            $where = array('status'=>self::STATUS_ISSUE, 'position_id'=>$position_id, 'type'=>$type);
            if ($is_thumb == self::THUMB_YES || ($is_thumb == self::THUMB_NO && $is_thumb != 'all')) {
                $where['thumb'] = $is_thumb;
            }
            $list = $this->where($where)->limit($limit)->order('sort desc, id desc')->select();
            if (!empty($list) && count($list) > 0) {
                cache($key, $list, $cache_time);
            } else {
                $list = array();
            }
        }

        return $list;
    }

    /**
     * 获取文章的推荐位信息
     * @param int $news_id  文章id
     * @return array
     */
    public function getNewsPositionIds($news_id = 0)
    {
        $where        = ['news_id'=>$news_id];
        $position_ids = $this->where($where)->column('position_id');
        return $position_ids;
    }
}
